package com.topisv.tms.web.stock.reverse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.SubWarehouseRel;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.stock.reverse.ReverseBill;
import com.topisv.tms.entity.stock.reverse.ReverseBillItem;
import com.topisv.tms.exception.ErrorCode;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.SubWarehouseRelService;
import com.topisv.tms.service.UserService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.reverse.ReverseBillItemService;
import com.topisv.tms.service.stock.reverse.ReverseBillService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.web.base.BaseController;

/**
 * 冲正单_control
 * @author ch
 */
@Controller
@RequestMapping({ "/v2/reverse" })
public class ReverseController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(ReverseController.class);

	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private ReverseBillService reverseBillService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private  ReverseBillItemService reverseBillItemService;
	@Autowired
	private UserService userService;
	@Autowired
	private SubWarehouseRelService subWarehouseRelService;
	/**
	 * 导向冲正单页面
	 * 
	 * @param pageNumber
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toReverseBillList")
	public String toReverseBillList(Model model, ServletRequest request) {
		try {
			// 查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList", customerList);
			model.addAttribute("userType", curUser.userType);

			// 如果是商家用户,初始化数据
			if ("customer".equals(curUser.userType)) {
				//商家编码 
				String customerCode = curUser.customerCode;
				model.addAttribute("customerCode", customerCode);
				// 初始化仓库数据
				List<AreaGroup> warehouseList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		} catch (Exception e) {
			
			logger.error("error",e);
		}

		return "stock/reverse/reverseBillList";
	}
	
	/**
	  * 数据源
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_reverse", method=RequestMethod.POST) 
    public void bindData_reverse(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<ReverseBill> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
           ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String status = paramMap.get("status");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
			param.put("status", status);
			
			//查询
			int curPage=(start/length)+1;
			page = this.reverseBillService.loadTask(param,curPage, length);
	        List<ReverseBill> billList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", billList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
       
		} catch (Exception e) {
			
		}
   } 
	 
   /**
	 * 导向冲正页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toReversePage/{billIdAndWarehouseCode}", method = RequestMethod.GET)
	public String toReversePage(@PathVariable("billIdAndWarehouseCode") String billIdAndWarehouseCode, Model model) {
		String[] strs = billIdAndWarehouseCode.split(",");
		Long billId = Long.valueOf(strs[0]);
		String warehouseCode = null ;
		if(strs.length>1&&!"".equals(strs[1])){
			warehouseCode = strs[1];
		}
		
		try {
			
			//查询冲正单
		    ReverseBill  bill=this.reverseBillService.loadById(billId);
		    if(warehouseCode != null) {
		    	this.reverseBillService.updateWarehouseCode(bill,warehouseCode);
		    }
		    
		    model.addAttribute("bill", bill);
		    
		    //查询冲正单明细
		    List<ReverseBillItem> itemList=this.reverseBillItemService.loadByBillCode(bill.getBillCode());
		    model.addAttribute("itemList", itemList);
		    
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/reverse/reverse";
	}
	
	/**
	 * 查询冲正数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping({ "ajaxQueryItem" })
	public String ajaxQueryItem(ServletRequest request,Model model,HttpServletResponse response) {
		try {
			
			//冲正明细数据
			Long billItemId =Long.valueOf(request.getParameter("billItemId"));
			ReverseBillItem billItem=this.reverseBillItemService.loadById(billItemId);
			
			//责任人
			List<User> dutyList=this.userService.loadByWarehouseCode(billItem.getWarehouseCode());
			
			JSONObject json = new JSONObject();
			json.put("billItem", billItem);
			json.put("dutyList", dutyList);
			PrintWriter out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
	/**
	 * 冲正
	 * @param request
	 * @param response
	 * @return
	 */
	 @RequestMapping(value={"ajaxReverse"}, method={RequestMethod.POST})
	 public void ajaxReverse(ServletRequest request,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
	    try {
	    	
	    	  json = new JSONObject();
			  out = response.getWriter();
	    	
		      Long billItemId =Long.valueOf(request.getParameter("billItemId"));
		      String dutyUuid = request.getParameter("dutyUuid");
		      
		      String stockCode = request.getParameter("stockCode");
		      String boxCode = request.getParameter("boxCode");
		      
		      String dutyReason = request.getParameter("dutyReason");
		      
		      
		      ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		      
		      //冲正
		      String msg=this.reverseBillItemService.reverse(billItemId, dutyUuid,dutyReason,stockCode,boxCode,curUser.jobuuid);
		      json.put("msg", msg);

	    } catch(PaiUException e){
	    	json.put("status","error");
			json.put("content",e.getMessage());
	    	if(ErrorCode.CUS_STOCK_NO_EXIST_ERROR.equals(e.getErrorCode())){
	    		json.put("msg", "nostock");
	    	}
			log.error("error",e);
	    }catch (Exception e) {
	    	
			json.put("status","error");
			json.put("content",e.getMessage());
			log.error("error",e);
	    }
	    
	    out.print(json.toString());
	  }

	 /**
		 * 预览冲正明细
		 * @param request
		 * @param response
		 * @return
		 */
	 @RequestMapping(value={"showDetail"}, method={RequestMethod.POST})
	 public void showDetail(Long billId,ServletRequest request,HttpServletResponse response) {
		 JSONObject json = new JSONObject();
		 PrintWriter out = null;
		 try {
			   //查询冲正单
			    ReverseBill  bill=this.reverseBillService.loadById(billId);
			    if(bill==null){
			    	json.put("status", "fail");
					out = response.getWriter();
					out.print(json);
					return;
			    }
			    //查询冲正单明细
			    List<ReverseBillItem> itemList=this.reverseBillItemService.loadByBillCode(bill.getBillCode());
				
				json.put("itemList", itemList);
				json.put("status", "success");
				out = response.getWriter();
				out.print(json);
			} catch (Exception e) {
				logger.error("error",e);
				json.put("status", "fail");
				try {
					out = response.getWriter();
				} catch (IOException e1) {
					logger.error("error",e1);
				}
				out.print(json);
			}
	 }
	 
	 /**
		 * 查询分仓
		 * @param model
		 * @param request
		 * @return
		 */
	 @RequestMapping(value={"querySubWarehouse"}, method={RequestMethod.POST})
		public void querySubWarehouse(Long billId,Model model,HttpServletResponse response) {
			 JSONObject json = new JSONObject();
			 PrintWriter out = null;
			 
			try {
				out = response.getWriter();
				
				List<AreaGroup> displayWarehouseList = new ArrayList<AreaGroup>();
				ReverseBill reverseBill = reverseBillService.loadById(billId);
				if(reverseBill==null){
					json.put("status", "fail");
					out.print(json.toString());
					return;
				}
				//获取子仓
				List<SubWarehouseRel> swrList = subWarehouseRelService.findByMainWarehouseCode(reverseBill.getWarehouseCode());
				
				fillSelectValue(model, reverseBill.getCustomerCode());
				
				@SuppressWarnings("unchecked")
				List<AreaGroup>  warehouseList = (List<AreaGroup>)model.asMap().get("warehouseList");
				for(AreaGroup areaGroup:warehouseList) {
					boolean result = false;
					if(areaGroup.getGroupCode().equals(reverseBill.getWarehouseCode())){
						result = true;
					}else {
						for(SubWarehouseRel r:swrList){
							if(r.getSubWarehouseCode()!=null && r.getSubWarehouseCode().equals(areaGroup.getGroupCode())){
								result = true;
								break;
							}
						}
					}
					if(result) {
						displayWarehouseList.add(areaGroup);
					}
				}
				json.put("warehouseList", displayWarehouseList);
				json.put("status", "success");
				out.print(json.toString());
			} catch (Exception e) {e.printStackTrace();
				logger.error("error",e);
				json.put("status", "fail");
				out.print(json.toString());
			}
		}
		

}